package com.sicheng.algorithm.array.sorted;

import java.util.Arrays;

import static com.sicheng.algorithm.common.Sort.swap;

public class QuickSorted {
    public static void main(String[] args) {
        int[] arr = {3, 4, 7, 8, 6, 9, 2};
        quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr) {

        if (arr != null && arr.length > 1) {
            quickSort(arr, 0, arr.length - 1);
        }
    }

    private static void quickSort(int[] arr, int start, int end) {

        int left = start, right = end, target = arr[start];

        while (left < right) {
            while (left < right) {
                if (arr[right] < target) {
                    swap(arr, left, right);
                    break;
                } else
                    right--;
            }

            while (left < right) {
                if (arr[left] > target) {
                    swap(arr, left, right);
                    break;
                } else left++;
            }
        }
        if (left - 1 > start) {
            quickSort(arr, start, left - 1);
        }
        if (right + 1 < end) {
            quickSort(arr, right + 1, end);
        }

    }
}
